#pragma once

#include <iostream>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstdlib>
#include <unistd.h>
#include "Common.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"


namespace SocketModule
{
    using namespace LogModule;
    const int defaultblock = 8;
    //虚基类
    class Socket
    {
    public:
        ~Socket(){}
        virtual void SocketOrDie() = 0;
        virtual void BindOrDie(uint16_t port) = 0;
        virtual void ListenOrDie(int block) = 0;
        virtual std::shared_ptr<Socket> Accept(Inet_Addr* addr) = 0;
        virtual void Close() = 0;
        virtual int Recv(std::string* out) = 0;
        virtual int Send(std::string& message) = 0;
        virtual int Connect(Inet_Addr& addr) = 0;

    public:
        //创建一个Tcp套接字(服务器)
        void BuildTcpServerSocketMethod(uint16_t port, int block = defaultblock)
        {
            SocketOrDie();
            BindOrDie(port);
            ListenOrDie(block);
        }
        //创建一个Tcp套接字(客户端)
        void BuildTcpClientSocketMethod()
        {
            
            SocketOrDie();
        }
    };

    //派生类
    class TcpSocket : public Socket
    {
    public:
        TcpSocket():_socketfd(-1){}
        TcpSocket(int socketfd):_socketfd(socketfd)
        {

        }
        void SocketOrDie()override
        {
            _socketfd = ::socket(AF_INET, SOCK_STREAM, 0);
            if(_socketfd < 0)
            {
                LOG(LogLevel::FATAL) << "Socket error";
                exit(SOCKET_ERR);
            }
            LOG(LogLevel::INFO) << "socket sussess: " << _socketfd;
        }
        void BindOrDie(uint16_t port)override
        {
            Inet_Addr addr(port);
            int n = ::bind(_socketfd, addr.INetAddr(), addr.NetAddrLen());
            if(n < 0)
            {
                LOG(LogLevel::FATAL) << "bind error";
                exit(BIND_ERR);
            }
            LOG(LogLevel::INFO) << "bind success: " << _socketfd;
        }
        void ListenOrDie(int block)override
        {
            int n = ::listen(_socketfd, block);
            if(n < 0)
            {
                LOG(LogLevel::FATAL) << "Listen error";
                exit(LISTEN_ERR);
            }
            LOG(LogLevel::INFO) << "Listen success: " << _socketfd;
        }
        std::shared_ptr<Socket> Accept(Inet_Addr* addr)override
        {
            //获取监听到的信息
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int n = ::accept(_socketfd, COVN(peer), &len);
            if(n < 0)
            {
                LOG(LogLevel::FATAL) << "accept error";
                exit(ACCEPT_ERR);
            }
            
            addr->SetAddr(peer);
            LOG(LogLevel::FATAL) << "accept success" << addr->StringAddr();
            //复用成员
            return std::make_shared<TcpSocket>(n);
        }
        void Close()override
        {
            if(_socketfd > 0)
                ::close(_socketfd);  
        }
        int Recv(std::string* out) override
        {
            //页面刷新不出不是缓冲区的问题
            char buffer[4096];
            ssize_t n = ::recv(_socketfd, buffer, sizeof(buffer) - 1, 0);
            
            if(n > 0)
            {
                buffer[n] = 0;
                *out += buffer;
            }
            return n;
        }
        int Send(std::string& message) override
        {
            // std::cout << message << std::endl;
            //printf("sockfd: %d\n", _socketfd);
            int n = ::send(_socketfd, message.c_str(), message.size(), 0);
            if(n < 0) {
                perror("send failed");
            }
            return n;
        }
        int Connect(Inet_Addr& addr) override
        {
            return ::connect(_socketfd, addr.INetAddr(), addr.NetAddrLen());
        }
    private:
        int _socketfd;
    };

}
